/**
 * Copyright (C), 2021-2021, Sakura有限公司(尚未成立)
 * FileName: TaosService
 * Author:   Sakura
 * Date:     2021/9/6 20:27
 * Description: 涛思数据的service层
 * History: 修改历史
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.casic.ccp.flying.youth.timeseriesdata.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.casic.ccp.flying.youth.timeseriesdata.model.SocketClient;
import com.casic.ccp.flying.youth.timeseriesdata.model.SqlPreparation;
import com.casic.ccp.flying.youth.timeseriesdata.model.WebSockeetData;
import com.casic.ccp.flying.youth.timeseriesdata.sql.SqlPreparationPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 〈一句话功能简述〉<br>
 * 〈涛思数据的service层〉
 *
 * @author: Sakura
 * @date: 2021/9/6
 */
@Service
@DS("taos")
public class JdbcService {

    /**
     * 日志记录器
     */
    private static Logger LOGGER = LoggerFactory.getLogger(JdbcService.class);
    /**
     * 数据库连接
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 对象池
     */
    @Autowired
    private SqlPreparationPool sqlPreparationPool;
    /**
     * 异步线程池插入数据
     * @param sqlPreparation
     * @param tableName
     */
    @Async("taskThreadPoolTaskExecutor")
    public void insertBatchData(SqlPreparation sqlPreparation, String tableName, SocketClient socketClient) {
        // sql 批量插入
        int update = 0;
        try {
            String sql = sqlPreparation.getSql(tableName);
            update = jdbcTemplate.update(sql);

        } catch (Exception e){
            LOGGER.error("数据插入错误",e);
        }finally {
            sqlPreparationPool.returnObject(sqlPreparation);
            // 告诉前端已插入
            socketClient.sendData(new WebSockeetData(2,0L).toString());
            LOGGER.info("已导入: {}",update);
        }
    }

}
